const { initSqlite3DB, queryProject } = require('../db')
const { checkDirectoryExistsSync } = require('../utils')
const path = require('path')




// 1. 判断 classid 对应目录是否存在
const checkClassDirExists = async (ctx, netx) => {
    const { classId } = ctx.params

    // 拼接上传文件存储目录
    const classDir = path.join(process.cwd(), 'uploads', classId)
   

    // 判断 classDir 目录是否存在
    if (!checkDirectoryExistsSync(classDir)) {
        ctx.body = {
            code: 404,
            message: `${classId} 班暂未开放项目提交权限`,
            projects: []
        }
        return
    }

    netx()
}

const getProjectList = async(ctx) => {
    // 从 URL 参数中获取 className
    const { classId } = ctx.params

    // 初始化数据库连接
    const db_path = path.join(process.cwd(), 'db/projectinfo.db')
    const db = initSqlite3DB(db_path)

    // 查询数据库获取项目列表
    const projects = queryProject(db, classId)

    db.close() // 关闭数据库连接
    ctx.body = {
        code: 200, 
         message: '获取项目列表成功',
        projects: projects
    }
    return 
}

// 导出
module.exports = {
    checkClassDirExists,
    getProjectList
}